import React, { memo, useCallback, useEffect, useState, useMemo } from 'react';
import { Descriptions, Spin, Tabs, Table, Tooltip, Icon, DatePicker } from 'antd';
import moment from 'moment';
import cn from 'classnames';

import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import SummaryTable from '@/components/SummaryTable';

import { salaryPayrollPrint } from '@/services/salaryManage/mySalary';
import { hrOverviewRecheck } from '@/services/salaryManage/salaryCalculate';
import {
    queryMySalaryBaseInfo,
    querySalaryHistory,
    queryKpiHistory,
    queryAttendHistory,
    querySalaryBaseYearMonth,
    queryTaxHistory
} from '@/services/salaryManage/employeeSalary';

import ChartWrapper from '@/pages/SalaryManage/components/ChartWrapper';
import NumberFormatter from '@/pages/SalaryManage/components/NumberFormatter';
import YearSelect from '@/pages/SalaryManage/components/YearSelect';
import { getCurrentOrgCountryCode } from '@/pages/SalaryManage/utils';
import { MONTHList } from '@/pages/SalaryManage/utils/staticList';

import {
    HISTORY_RECORD_LIST,
    baseInfoOfCountry,
    baseInfoFilter,
    QuestionTitle,
    NumberTypeTd
} from '@/pages/SalaryManage/constant/mySalaryContext';
import { SINGAPORE_CODE } from '@/pages/SalaryManage/constant/countryRegion';

import styles from './index.less';

const { TabPane } = Tabs;

const { MonthPicker } = DatePicker;

// 员工基础信息
const BaseInfo = memo(({ countryCode, employeeCode, organizationCode }) => {
    const [loading, setLoading] = useState(false);
    const [baseInfo, setBaseInfo] = useState({});
    const getInfo = useCallback(async () => {
        try {
            setLoading(true);
            const { code, data = {} } = await queryMySalaryBaseInfo(employeeCode, organizationCode);
            if (code === 10000) {
                console.log('基础信息', data);
                setBaseInfo(data);
            }
            setLoading(false);
        } catch (e) {
            console.log(e);
            setLoading(false);
        }
    }, [employeeCode, organizationCode]);
    useEffect(() => {
        getInfo();
    }, [getInfo]);

    return (
        <Spin spinning={loading}>
            <div className={styles.container}>
                <div className={styles.salaryContent}>
                    <div className={styles.titleWrap}>
                        <div className={styles.title}>员工基础信息</div>
                    </div>
                    <Descriptions>
                        {Object.entries(baseInfoOfCountry(countryCode)).map(item => (
                            <Descriptions.Item
                                key={item[0]}
                                label={<span className={styles.infoLabel}>{item[1]}</span>}
                            >
                                {baseInfoFilter(baseInfo[item[0]], item[0])}
                            </Descriptions.Item>
                        ))}
                    </Descriptions>
                </div>
                <div className={cn(styles.salaryContent, styles.noBorder)}>
                    <div className={styles.titleWrap}>
                        <div className={styles.title}>薪资基础信息</div>
                    </div>
                    <Descriptions>
                        <Descriptions.Item label={<span className={styles.infoLabel}>基本月薪</span>}>
                            <span className={styles.currency}>
                                <NumberFormatter value={baseInfo.encryptBaseSalaryAmt} />
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label={<span className={styles.infoLabel}>月绩效工资</span>}>
                            <span className={styles.currency}>
                                <NumberFormatter value={baseInfo.encryptKpiMonthAmt} />
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label={<span className={styles.infoLabel}>年薪</span>}>
                            <span className={styles.currency}>
                                <NumberFormatter value={baseInfo.encryptTotalSalaryAmt} />
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label={<span className={styles.infoLabel}>年终奖</span>}>
                            <span className={styles.currency}>
                                <NumberFormatter value={baseInfo.encryptEndYearAmt} />
                            </span>
                        </Descriptions.Item>
                        <Descriptions.Item label={<span className={styles.infoLabel}>半年奖</span>}>
                            <span className={styles.currency}>
                                <NumberFormatter value={baseInfo.encryptHalfYearAmt} />
                            </span>
                        </Descriptions.Item>
                    </Descriptions>
                </div>
            </div>
        </Spin>
    );
});

// 薪资分析表
const ChartInfo = memo(({ employeeCode, yearMonth, organizationCode }) => {
    const [loading, setLoading] = useState(false);
    const [salaryChartList, setSalaryChartList] = useState([]);
    const [periodMoment, setPeriodMoment] = useState(undefined);
    const [year, setYear] = useState('');
    const [month, setMonth] = useState('');
    useEffect(() => {
        if (yearMonth) {
            const date = moment(yearMonth);
            setPeriodMoment(date);
            setYear(date.format('YYYY'));
            setMonth(date.format('MM'));
        }
    }, [yearMonth]);
    const getInfo = useCallback(async () => {
        try {
            setLoading(true);
            const { code, data = {} } = await hrOverviewRecheck.querySalaryRecheckDataChartType({
                employeeCode,
                year,
                month,
                organizationCode
            });
            if (code === 10000) {
                setSalaryChartList(data.salaryRecheckDiagramTypListVOList || []);
            }
            setLoading(false);
        } catch (e) {
            console.log(e);
            setLoading(false);
        }
    }, [employeeCode, month, organizationCode, year]);
    useEffect(() => {
        if (year && month) {
            getInfo();
        }
    }, [year, month, getInfo]);

    const onChange = (date, dateString) => {
        const time = moment(dateString);
        setPeriodMoment(time);
        setYear(time.format('YYYY'));
        setMonth(time.format('MM'));
    };

    const disabledDate = current => current && current > moment(yearMonth).endOf('day');

    return (
        <Spin spinning={loading}>
            <div className={styles.container}>
                <div className={styles.salaryContent}>
                    <div className={styles.titleWrap}>
                        <div className={styles.title}>
                            薪资分析表
                            <MonthPicker
                                onChange={onChange}
                                size="small"
                                suffixIcon={<Icon type="down" />}
                                value={periodMoment}
                                disabledDate={disabledDate}
                                style={{ width: '110px', marginLeft: 20 }}
                                allowClear={false}
                            />
                        </div>
                    </div>
                    {salaryChartList.map(item => (
                        <ChartWrapper
                            {...item}
                            key={item.diagramTypeName}
                            year={year}
                            month={month}
                            employeeCode={employeeCode}
                            organizationCode={organizationCode}
                        />
                    ))}
                </div>
            </div>
        </Spin>
    );
});

const History = memo(({ location, yearMonth, organizationCode, countryCode }) => {
    const { query } = location;
    const { active, employeeCode } = query;
    const [historyLoading, setHistoryLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [columns, setColumns] = useState({});
    const [currentSelectYear, setCurrentSelectYear] = useState(null);
    const [currentTabKey, setCurrentTabKey] = useState('salaryRecords');
    const [periodMoment, setPeriodMoment] = useState(null);

    useEffect(() => {
        if (yearMonth) {
            setPeriodMoment(moment(yearMonth));
        }
    }, [yearMonth]);

    useEffect(() => {
        if (active) {
            switch (active) {
                case '2':
                    setCurrentTabKey('kpiRecords');
                    break;
                case '3':
                    setCurrentTabKey('attendRecords');
                    break;
                case '4':
                    setCurrentTabKey('taxRecords');
                    break;
                default:
                    setCurrentTabKey('salaryRecords');
                    break;
            }
        }
    }, [active]);

    // 薪资记录-默认的表格头
    const SALARY_HISTORY_COLUMN = useMemo(
        () => [
            {
                title: '月份',
                dataIndex: 'month',
                key: 'month',
                width: 90,
                align: 'center',
                render: t => (MONTHList[t - 1] ? MONTHList[t - 1].monthName : '合计')
            },
            {
                title: <QuestionTitle text="薪资总额" title="薪资总额=全部薪资的加项" />,
                dataIndex: 'encryptTotalAmt',
                key: 'encryptTotalAmt',
                width: 150,
                align: 'right',
                render: t => <NumberTypeTd value={t} />
            },
            {
                title: <QuestionTitle text="实发薪资" title="实发薪资=全部薪资加项-全部减项-险金-个人所得税" />,
                dataIndex: 'encryptTotalPayAmt',
                key: 'encryptTotalPayAmt',
                width: 150,
                align: 'right',
                render: t => <NumberTypeTd value={t} />
            }
        ],
        []
    );

    const salaryExportFn = useCallback(
        (payrollId, data) => {
            salaryPayrollPrint({
                organizationCode,
                payrollId
            }).then(res => {
                const URL = window.URL || window.webkitURL;
                const objectUrl = URL.createObjectURL(res.data);
                const a = document.createElement('a');
                a.href = objectUrl;
                a.download = `${currentSelectYear}-${data.month}薪资单`;
                document.body.appendChild(a);
                a.click();
                a.remove();
            });
        },
        [currentSelectYear, organizationCode]
    );

    const SALARY_HISTORY_COLUMN_ACTION = useMemo(
        () =>
            countryCode === SINGAPORE_CODE
                ? [
                      {
                          title: '操作',
                          dataIndex: 'payrollId',
                          key: 'payrollId',
                          width: 100,
                          fixed: 'right',
                          align: 'center',
                          render: (t, c) =>
                              MONTHList[c.month - 1] ? (
                                  <Tooltip placement="top" title="下载">
                                      <i
                                          className={cn(
                                              'icon',
                                              'iconfont',
                                              'icontarentiaogangshenqing1',
                                              styles.exportIcon
                                          )}
                                          onClick={() => salaryExportFn(t, c)}
                                      ></i>
                                  </Tooltip>
                              ) : null
                      }
                  ]
                : [],
        [countryCode, salaryExportFn]
    );

    // 薪资记录-组装表头
    const handleHeaderData = useCallback(
        (data = []) =>
            data.map(item =>
                item.children.length
                    ? {
                          ...item,
                          align: 'center',
                          children: handleHeaderData(item.children)
                      }
                    : {
                          ...item,
                          align: 'right',
                          children: null,
                          width: 120,
                          render: text => (
                              <span
                                  className={cn({
                                      [styles.tableColorRed]: item.colorControl === 1 || text < 0
                                  })}
                              >
                                  <NumberTypeTd value={text} />
                              </span>
                          )
                      }
            ),
        []
    );

    // 考勤记录-组装表头
    const attendHeaderData = useCallback(
        (data = []) =>
            data.map(item =>
                item.children.length
                    ? {
                          ...item,
                          children: attendHeaderData(item.children)
                      }
                    : {
                          ...item,
                          align: 'center',
                          children: null
                      }
            ),
        []
    );

    // 切换年份
    const onSetCurrentYear = useCallback(year => {
        setCurrentSelectYear(year);
    }, []);

    // 获取薪资记录
    const getSalaryHistory = useCallback(async () => {
        try {
            const { code, data = {} } = await querySalaryHistory(employeeCode, currentSelectYear);
            if (code === 10000) {
                setColumns({
                    ...columns,
                    salaryRecords: [
                        ...SALARY_HISTORY_COLUMN,
                        ...handleHeaderData(data.headerStaffItems || []),
                        ...handleHeaderData(data.headerSalaryItems || []),
                        ...SALARY_HISTORY_COLUMN_ACTION
                    ]
                });
                setTableData(data.data || {});
            }
            setHistoryLoading(false);
        } catch (e) {
            console.log(e);
            setHistoryLoading(false);
        }
    }, [
        SALARY_HISTORY_COLUMN,
        SALARY_HISTORY_COLUMN_ACTION,
        columns,
        currentSelectYear,
        employeeCode,
        handleHeaderData
    ]);

    // 获取绩效系数记录
    const getKpiHistory = useCallback(async () => {
        try {
            const { code, data = {} } = await queryKpiHistory(employeeCode, currentSelectYear);
            if (code === 10000) {
                setTableData(data);
            }
            setHistoryLoading(false);
        } catch (e) {
            setHistoryLoading(false);
        }
    }, [currentSelectYear, employeeCode]);

    // 获取专项扣除
    const getTaxHistory = useCallback(async () => {
        try {
            const { code, data = {} } = await queryTaxHistory(employeeCode, currentSelectYear);
            if (code === 10000) {
                setTableData(data);
            }
            setHistoryLoading(false);
        } catch (e) {
            setHistoryLoading(false);
        }
    }, [currentSelectYear, employeeCode]);

    // 获取考勤-到月份
    const getAttendHistory = useCallback(
        async val => {
            try {
                const attendYear = moment(val).format('YYYY');
                const attendMonth = moment(val).format('MM');
                const { code, data } = await queryAttendHistory(employeeCode, attendYear, attendMonth);
                if (code === 10000) {
                    if (code === 10000) {
                        setColumns({
                            ...columns,
                            attendRecords: attendHeaderData(data.tableHeader || [])
                        });
                        setTableData(data.item || {});
                    }
                }
                setHistoryLoading(false);
            } catch (e) {
                setHistoryLoading(false);
            }
        },
        [attendHeaderData, columns, employeeCode]
    );

    // 切换tab
    const onTabsChange = useCallback(
        key => {
            setHistoryLoading(true);
            setTableData([]);
            switch (key) {
                case 'salaryRecords':
                    getSalaryHistory();
                    break;
                case 'kpiRecords':
                    getKpiHistory();
                    break;
                case 'attendRecords':
                    getAttendHistory(periodMoment);
                    break;
                case 'taxRecords':
                    getTaxHistory();
                    break;
                default:
            }
        },
        [getAttendHistory, getKpiHistory, getSalaryHistory, getTaxHistory, periodMoment]
    );

    // 考勤记录-月份切换
    const onAttendMonthChange = (e, date) => {
        setPeriodMoment(moment(date));
        getAttendHistory(date);
    };

    useEffect(() => {
        if (currentSelectYear) {
            onTabsChange(currentTabKey);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentSelectYear, currentTabKey]);

    const disabledDate = current => current && current > moment(yearMonth).endOf('day');

    return (
        <Spin spinning={historyLoading}>
            <div className={styles.container}>
                <div className={styles.titleWrap}>
                    <div className={styles.leftTitleWrap}>
                        <div className={styles.title}>薪资历史记录</div>
                        <YearSelect
                            value={currentSelectYear}
                            onChange={onSetCurrentYear}
                            organizationCode={organizationCode}
                            styles={{
                                display: currentTabKey === 'attendRecords' ? 'none' : 'initial'
                            }}
                        />
                        {currentTabKey === 'attendRecords' ? (
                            <MonthPicker
                                onChange={onAttendMonthChange}
                                size="small"
                                suffixIcon={<Icon type="down" />}
                                value={periodMoment}
                                disabledDate={disabledDate}
                                style={{
                                    width: '110px'
                                }}
                                allowClear={false}
                            />
                        ) : null}
                    </div>
                </div>
                <div className={cn(styles.tabsWrap, styles.salaryContent)}>
                    <Tabs
                        animated={false}
                        activeKey={currentTabKey}
                        onChange={key => {
                            setCurrentTabKey(key);
                        }}
                    >
                        {HISTORY_RECORD_LIST.filter(item => !item.countryCode || item.countryCode === countryCode).map(
                            tab => (
                                <TabPane tab={tab.name} key={tab.key}>
                                    {tab.key === 'taxRecords' ? (
                                        <SummaryTable
                                            bordered
                                            columns={tab.columns || columns[tab.key] || []}
                                            rowKey="key"
                                            dataSource={tableData}
                                            pagination={false}
                                            vvSummaryFields={[
                                                {
                                                    yearMonth: '合计'
                                                },
                                                'encryptCurrChildEducationAmt',
                                                'encryptCurrContinueEducationAmt',
                                                'encryptCurrHouseLeaseAmt',
                                                'encryptCurrHouseLoanInterestAmt',
                                                'encryptCurrRaiseOldAmt',
                                                'encryptCurrSpecialAmt'
                                            ]}
                                            hideSelection
                                            vvForceToFit
                                        />
                                    ) : (
                                        <Table
                                            columns={tab.columns || columns[tab.key] || []}
                                            dataSource={tableData}
                                            bordered
                                            pagination={false}
                                            scroll={{
                                                x: 'max-content'
                                            }}
                                            rowKey="key"
                                        />
                                    )}
                                </TabPane>
                            )
                        )}
                    </Tabs>
                </div>
            </div>
        </Spin>
    );
});
const EmployeeSalary = ({ location }) => {
    const { query } = location;
    const { employeeCode, organizationCode } = query;
    const [yearMonth, setYearMonth] = useState();
    useEffect(() => {
        if (employeeCode) {
            querySalaryBaseYearMonth(employeeCode).then(res => {
                const { code, data } = res;
                if (code === 10000) {
                    setYearMonth(data);
                }
            });
        }
    }, [employeeCode]);

    const employeeCountryCode = useMemo(() => getCurrentOrgCountryCode(organizationCode), [organizationCode]);

    return (
        <PageHeaderWrapper>
            <BaseInfo
                countryCode={employeeCountryCode}
                employeeCode={employeeCode}
                organizationCode={organizationCode}
            />
            <History
                countryCode={employeeCountryCode}
                location={location}
                yearMonth={yearMonth}
                organizationCode={organizationCode}
            />
            <ChartInfo employeeCode={employeeCode} yearMonth={yearMonth} organizationCode={organizationCode} />
        </PageHeaderWrapper>
    );
};

export default withRoutePage(EmployeeSalary);
